//
//  SASupplierVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/2.
//

#import "SASupplierVC.h"
#import "SAProviderListAPI.h"
#import "SASupplierCell.h"
#import "SAProductManufacturerModel.h"
#import "SAAddSupplierView.h"
#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"
#import "BubbleTableView.h"

@interface SASupplierVC ()<UITextFieldDelegate,UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITextField *searchTf;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) SAProviderListAPI *providerListAPI;
@property (nonatomic, strong) NSMutableArray<SAProductManufacturerModel *> *dataMarr;
@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, strong) UILabel *allShopLab;
@property (nonatomic, strong) UIImageView *allowImageV2;
@property (nonatomic, strong) UIButton *topBtn;

@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreModel *> *storeList;
@property (nonatomic, strong) BubbleTableView *storeBubbleView;
@property (nonatomic, assign) NSInteger storeRow;

@end

@implementation SASupplierVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.providerListAPI == api) {
        if (self.currentPage == 1) {
            self.dataMarr = [SAProductManufacturerModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        }else {
            NSMutableArray *marr = [SAProductManufacturerModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
            for (SAProductManufacturerModel *model in marr) {
                [self.dataMarr addObject:model];
            }
        }
        [self.tableView reloadData];
        self.tipView.hidden = (self.dataMarr.count > 0);
    }else if (self.systemStoreStoreListAPI == api) {
        self.storeList = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        for (NSInteger i = 0; i < self.storeList.count; i++) {
            if ([SAValueManger shareInStance].userInfo.merchantId == self.storeList[i].merchantId) {
                self.storeRow = i;
            }
        }
        [self showStoreList];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableView Delegate & DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASupplierCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASupplierCell"];
    cell.model = self.dataMarr[indexPath.section];
    WeakSelf
    cell.iphoneBlock = ^(NSString * _Nonnull iphoneStr) {
        [weakSelf clickedIphone:iphoneStr];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SAAddSupplierView *addSupplierView = [SAAddSupplierView shareCornView];
    addSupplierView.model = self.dataMarr[indexPath.section];
    [addSupplierView showView:self];
    WeakSelf
    addSupplierView.refreshBlock = ^{
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    };
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(55);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

#pragma mark - UITextField
- (void)textFieldEditChanged:(UITextField *)textField {
    self.providerListAPI.providerName = textField.text;
    self.currentPage = 1;
    [self loadData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
   return YES;
}

#pragma mark - event
-(void)clickedAddBtn {
    SAAddSupplierView *addSupplierView = [SAAddSupplierView shareCornView];
    [addSupplierView showView:self];
    WeakSelf
    addSupplierView.refreshBlock = ^{
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    };
}

-(void)loadData {
    self.providerListAPI.currentPage = self.currentPage;
    [self.providerListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(void)clickedIphone:(NSString *)iphoneStr {
    NSMutableString *str= [[NSMutableString alloc] initWithFormat:@"telprompt://%@",iphoneStr];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:[NSDictionary dictionary] completionHandler:nil];
}

-(void)clickedAllowBtn2 {
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *crossStoreProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"crossStoreProvider"]];
    if ([crossStoreProvider isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有跨店查供货商权限,请联系店长添加" duration:2];
        return;
    }
    
    if (self.storeList.count > 0) {
        [self showStoreList];
    }else {
        self.systemStoreStoreListAPI.returnAll = @"false";
        [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}
    
-(void)showStoreList{
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreModel *model in self.storeList) {
        if (model.storeName.length == 0) {
            model.storeName = @"";
        }
        [marr addObject:model.storeName];
    }
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.storeBubbleView) {
        self.storeBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.storeRow = row;
            self.providerListAPI.merchantId = @(self.storeList[row].merchantId).stringValue;
            self.allShopLab.text = rowString;
            self.currentPage = 1;
            self.providerListAPI.currentPage = 1;
            [self loadData];
        } hideBlock:^{
            self.storeBubbleView = nil;
        }];
        [self.storeBubbleView showWithTargetView:self.allowImageV2 maskSuperView:window];
        [self.storeBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.storeBubbleView.bubbleCellHeight = 50;
        self.storeBubbleView.selectRow = self.storeRow;
        self.storeBubbleView.isBubbleScrollEnabled = YES;
        self.storeBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

-(void)clickedTopBtn {
    if (self.dataMarr.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        [self.tableView reloadData];
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"供货商"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    
    [self addRightViews:@[self.topView]];
    [self.topView addSubview:self.searchTf];
    [self.topView addSubview:self.addBtn];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topBtn];
    [self.view addSubview:self.tipView];
    
    UIView *grayView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 35)];
    grayView.backgroundColor = kTextBgColor;
    [self.view addSubview:grayView];
    
    UILabel *allShopLab = [[UILabel alloc] init];
    allShopLab.text = [SAValueManger shareInStance].userInfo.storeName;
    allShopLab.font = kBFont(15);
    allShopLab.textColor = kBlackColor;
    [grayView addSubview:allShopLab];
    self.allShopLab = allShopLab;
    
    UIImageView *allowImageV2 = [[UIImageView alloc] init];
    allowImageV2.image = [UIImage imageNamed:@"bule_downAllow"];
    [grayView addSubview:allowImageV2];
    allowImageV2.contentMode = UIViewContentModeCenter;
    self.allowImageV2 = allowImageV2;
    
    UIButton *allowBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [allowBtn2 addTarget:self action:@selector(clickedAllowBtn2) forControlEvents:UIControlEventTouchUpInside];
    [grayView addSubview:allowBtn2];
    
    [allShopLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(kScaleNum(25));
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_lessThanOrEqualTo(kScaleNum(150));
        make.width.mas_greaterThanOrEqualTo(kScaleNum(50));
    }];
    
    [allowImageV2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.width.mas_equalTo(kScaleNum(55));
        make.left.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(-10));
    }];
    
    [allowBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(0);
        make.height.mas_equalTo(kScaleNum(35));
        make.right.mas_equalTo(allShopLab.mas_right).offset(kScaleNum(30));
    }];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage = 1;
        [weakSelf loadData];
    }];
    MJRefreshAutoStateFooter *mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf.view endEditing:YES];
        weakSelf.currentPage ++;
        [weakSelf loadData];
    }];
    [mj_footer setTitle:@"已经到底啦~" forState:MJRefreshStateIdle];//设置闲置状态下不显示“点击或上拉加载更多”
    self.tableView.mj_footer = mj_footer;
    
    self.currentPage = 1;
    self.providerListAPI.pageSize = @"20";
    self.providerListAPI.merchantId = @([SAValueManger shareInStance].userInfo.merchantId).stringValue;
    
    [self loadData];
}

#pragma mark - lazy
-(UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:SARectMake(63, 0, 312, 44)];
    }
    return _topView;
}

-(UITextField *)searchTf {
    if (!_searchTf) {
        _searchTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
        _searchTf.placeholder = @"请输入供货商名称/手机号";
        _searchTf.backgroundColor = [UIColor whiteColor];
        _searchTf.layer.cornerRadius = kScaleNum(5);
        _searchTf.layer.masksToBounds = YES;
        _searchTf.delegate = self;
        _searchTf.font = kFont(14);
        _searchTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIView *leftView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 26, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(6, 7, 14, 16)];
        imageV.image = [UIImage imageNamed:@"shop_search"];
        [leftView addSubview:imageV];
        _searchTf.leftView = leftView;
        _searchTf.leftViewMode = UITextFieldViewModeAlways;
        _searchTf.returnKeyType = UIReturnKeyDone;
        [_searchTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTf;
}

-(UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setImage:[UIImage imageNamed:@"white_add"] forState:UIControlStateNormal];
        _addBtn.frame = SARectMake(254, 0, 53, 44);
        [_addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 35), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 35)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SASupplierCell class] forCellReuseIdentifier:@"SASupplierCell"];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
    }
    return _tableView;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight))];
        _tipView.backgroundColor = kLineColor;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = SARectMake(124, 150, 138, 83);
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}

-(SAProviderListAPI *)providerListAPI {
    if (!_providerListAPI) {
        _providerListAPI = [SAProviderListAPI apiWithDelegate:self];
    }
    return _providerListAPI;
}

-(NSMutableArray<SAProductManufacturerModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIButton *)topBtn {
    if (!_topBtn) {
        _topBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _topBtn.frame = CGRectMake(kScreenWidth - kScaleNum(80), kScreenHeight - kScaleNum(80), kScaleNum(48), kScaleNum(48));
        [_topBtn setImage:[UIImage imageNamed:@"shop_topBtn2"] forState:UIControlStateNormal];
        [_topBtn addTarget:self action:@selector(clickedTopBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _topBtn;
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

-(NSMutableArray<SAStoreModel *> *)storeList {
    if (!_storeList) {
        _storeList = [NSMutableArray array];
    }
    return _storeList;
}

@end
